package com.wj.facedetect.activity.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wj.facedetect.R;
import com.wj.facedetect.activity.base.BaseActivity;
import com.wj.facedetect.bean.home.GetDetectionHeadBean;
import com.wj.facedetect.bean.home.RefactorBean;
import com.wj.facedetect.presenter.HomePresenter;
import com.wj.facedetect.util.CameraUtil;
import com.wj.facedetect.util.CommonUtils;
import com.wj.facedetect.util.DialogUtil;
import com.wj.facedetect.util.PreferencesUtils;
import com.wj.facedetect.util.ToastUtil;
import com.wj.facedetect.view.IBaseView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tangkun on 2018/3/30.
 */

public class OneToNPreActiviy extends BaseActivity implements View.OnClickListener, IBaseView {
    private static final String TAG = "OneToNPreActiviy";
    private TextView tvLeft;
    private TextView tvRight;
    private ImageView ivPhoto;
    private TextView tvCompare;
    private String photoUri;
    private static final String KEY_PHOTO_URI = "photo_uri";
    private HomePresenter homePresenter;
    private final int TYPE_DETECTION = 0x001;//人脸识别
    private final int TYPE_REFACTR = TYPE_DETECTION + 1;//1比N
    private int requestType = TYPE_DETECTION;
    private Bitmap srcBitmap;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_to_n_pre);
        photoUri = getIntent().getStringExtra(KEY_PHOTO_URI);
        homePresenter = new HomePresenter(this);
        initView();
        srcBitmap = CameraUtil.handlePhotoByDecodeAndRotate(this, photoUri);
        if (srcBitmap != null) {
            ivPhoto.setImageBitmap(srcBitmap);
        }
        requestType = TYPE_DETECTION;
        requestData();
    }

    private void initView() {
        tvLeft = (TextView) findViewById(R.id.tv_left);
        tvRight = (TextView) findViewById(R.id.tv_right);
        ivPhoto = (ImageView) findViewById(R.id.iv_photo);
        tvCompare = (TextView) findViewById(R.id.tv_compare);
        tvLeft.setOnClickListener(this);
        tvRight.setOnClickListener(this);
        tvCompare.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.tv_right:
                setResult(RESULT_FIRST_USER);
                finish();
                break;
            case R.id.tv_compare:
                // TODO: 2018/3/30
                if (x == Integer.MIN_VALUE) {
                    Toast.makeText(this, "未识别出人脸,请重新采集!", Toast.LENGTH_SHORT).show();
                    return;
                }
                requestType = TYPE_REFACTR;
                requestData();
                break;
        }
    }

    public void requestData() {
        if (requestType == TYPE_DETECTION) {//人脸识别
            if (srcBitmap == null) {
                return;
            }
            Map<String, Object> optionsMap = new HashMap<>();
            optionsMap.put("max_faces_allowed", -1);
            //
            Map<String, Object> map = new HashMap<>();
            map.put("options", optionsMap);
            String base64 = CommonUtils.bitmapToBase64(srcBitmap);
            base64 = base64.replace("\n", "");
            map.put("image_content_base64", base64);
            Gson gson = new Gson();
            String params = gson.toJson(map);
            showProgressDialog();
            homePresenter.doRequestDetectionTemp(params, TYPE_DETECTION, this);
        } else if (requestType == TYPE_REFACTR) {//1比N
            if (srcBitmap == null) {
                return;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("cluster_id", PreferencesUtils.getInstance().getSharePreStrClusterId(PreferencesUtils.CLUSTER_ID));
            Map<String, Object> orderMap = new HashMap<>();
//            orderMap.put("similarity", -1);
            orderMap.put("similarity", 40);
            map.put("order", orderMap);
            map.put("start", 0);
            map.put("limit", 100);

            List<String> fieldList = new ArrayList<>();
            fieldList.add("face_image_id");
            fieldList.add("repository_id");
            fieldList.add("timestamp");
            fieldList.add("person_id");
            fieldList.add("name");
            fieldList.add("gender");
            fieldList.add("nation");
            fieldList.add("camera_id");
            fieldList.add("is_hit");
            fieldList.add("born_year");
            fieldList.add("picture_uri");
            fieldList.add("face_image_uri");
            fieldList.add("face_rect");
            fieldList.add("multi_frame_face_image_uris");
            fieldList.add("multi_frame_picture_uris");
            fieldList.add("multi_frame_face_rects");
            fieldList.add("rec_glasses");
            fieldList.add("rec_fringe");
            fieldList.add("rec_uygur");
            fieldList.add("rec_gender");
            fieldList.add("rec_age");
            fieldList.add("rec_age_range");
            fieldList.add("similarity");
            fieldList.add("annotation");
            fieldList.add("case_number");
            fieldList.add("remark");
            map.put("fields", fieldList);

            map.put("condition", new HashMap<>());
            map.put("query_meta", new HashMap<>());

            Map<String, Object> retrievalMap = new HashMap<>();
            String base64 = CommonUtils.bitmapToBase64(srcBitmap);
            base64 = base64.replace("\n", "");
            retrievalMap.put("image_content_base64", base64);
            retrievalMap.put("threshold", 0);
            retrievalMap.put("using_ann", true);

            Map<String, Object>[] repositoryMapArray = new Map[1];
            Map<String, Object> repositoryMap = new HashMap<>();
            repositoryMap.put("repository_id", PreferencesUtils.getInstance().getSharePreInt(PreferencesUtils.KU_ID) + "@" + PreferencesUtils.getInstance().getSharePreStrClusterId(PreferencesUtils.CLUSTER_ID));
            repositoryMapArray[0] = repositoryMap;
            retrievalMap.put("repository_list", repositoryMapArray);

            Map<String, Integer> faceRectMap = new HashMap<>();
            if (x != Integer.MIN_VALUE) {
                faceRectMap.put("h", h);
                faceRectMap.put("w", w);
                faceRectMap.put("x", x);
                faceRectMap.put("y", y);
            }
            retrievalMap.put("face_rect", faceRectMap);

            map.put("retrieval", retrievalMap);
            //
            Gson gson = new Gson();
            String params = gson.toJson(map);
            Log.i(TAG, params);
            showProgressDialog();
            homePresenter.doRequestRefactorTemp(params, TYPE_REFACTR, this);
        }
    }

    private int x = Integer.MIN_VALUE;
    private int y = Integer.MIN_VALUE;
    private int w = Integer.MIN_VALUE;
    private int h = Integer.MIN_VALUE;


    public static void startActivity(Activity activity, Fragment fragment, String photoUri, int reqCode) {
        Context context;
        if (activity != null) {
            context = activity;
        } else if (fragment != null) {
            context = fragment.getContext();
        } else {
            return;
        }
        Intent intent = new Intent(context, OneToNPreActiviy.class);
        intent.putExtra(KEY_PHOTO_URI, photoUri);
        //CameraUtil.grantPermission(context, intent, photoUri);
        if (activity != null) {
            activity.startActivityForResult(intent, reqCode);
        } else if (fragment != null) {
            fragment.startActivityForResult(intent, reqCode);
        } else {
            return;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onSuccess(int what, Object data, Object carryObj) {
        dismissProgressDialog();
        switch (what) {
            case TYPE_DETECTION:
                //获取头像信息
                GetDetectionHeadBean getDetectionHeadBean = (GetDetectionHeadBean) data;
                if (getDetectionHeadBean != null) {
                    if (getDetectionHeadBean.getRtn() == 0) {
                        List<GetDetectionHeadBean.ResultsBean> results = getDetectionHeadBean.getResults();
                        if (results.size() > 0) {
                            GetDetectionHeadBean.ResultsBean resultsBean = results.get(0);
                            GetDetectionHeadBean.ResultsBean.FaceRectBean face_rect = resultsBean.getFace_rect();
                            if (face_rect != null) {
                                x = face_rect.getX();
                                y = face_rect.getY();
                                w = face_rect.getW();
                                h = face_rect.getH();
                            } else {
                                x = Integer.MIN_VALUE;
                                y = Integer.MIN_VALUE;
                                w = Integer.MIN_VALUE;
                                h = Integer.MIN_VALUE;
                                DialogUtil.showErrorMsg(this, "未识别出人脸,请重新采集!");
                            }

                        } else {
                            x = Integer.MIN_VALUE;
                            y = Integer.MIN_VALUE;
                            w = Integer.MIN_VALUE;
                            h = Integer.MIN_VALUE;
                            DialogUtil.showErrorMsg(this, "未识别出人脸,请重新采集!");
                        }

                    } else {
                        x = Integer.MIN_VALUE;
                        y = Integer.MIN_VALUE;
                        w = Integer.MIN_VALUE;
                        h = Integer.MIN_VALUE;
                        DialogUtil.showErrorMsg(this, "未识别出人脸,请重新采集!");
                    }
                }
                break;
            case TYPE_REFACTR:
                //获取对比结果
                RefactorBean refactorBean = (RefactorBean) data;
                if (refactorBean != null) {
                    if (refactorBean != null) {//查询成功
                        List<RefactorBean.ResultsBean> results = refactorBean.getResults();
                        if (results != null && !results.isEmpty()) {//有匹配结果
                            Intent intent = new Intent(OneToNPreActiviy.this, FaceCheckResult2Activity.class);
                            intent.putExtra("refactorBean", refactorBean);
                            startActivity(intent);
                            finish();
                        } else {//无匹配结果
                            DialogUtil.showErrorMsg(this, "无比对结果!");
                        }
                    } else {//查询识失败
                        DialogUtil.showErrorMsg(this, "比对异常!");
                    }
                }
                break;
        }
    }

    @Override
    public void onError(int what, Exception e, Object carryObj) {
        dismissProgressDialog();
        ToastUtil.showMessage("网络异常");
    }

    @Override
    public void onFail(int what, int errorCode, String errorMsg, Object carryObj) {
        dismissProgressDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        homePresenter.getModel().cancleRequest(this);
    }
}
